package main.leetcode.offer.firstround.from03to50;

import main.datastruc.ListNode;

import java.util.Stack;

/**
 * 06.从尾到头打印链表 输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。
 *
 * <p>示例 1： 输入：head = [1,3,2] 输出：[2,3,1]
 *
 * <p>限制： 0 <= 链表长度 <= 10000
 *
 * <p>来源：力扣（LeetCode） 链接：https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class ex06 {

    public int[] reversePrint(ListNode head) {
        Stack<Integer> stack = new Stack<>();
        ListNode pre = head;
        while (pre != null) {
            stack.push(pre.val);
            pre = pre.next;
        }
        int[] nums = new int[stack.size()];
        int i = 0;
        while (!stack.isEmpty()) nums[i++] = stack.pop();

        return nums;
    }

    public int[] reversePrint1(ListNode head) {
        int n = 0;
        ListNode pre = head;
        while (pre != null) {
            n++;
            pre = pre.next;
        }
        int[] nums = new int[n];
        ListNode p = head;
        int i = n - 1;
        while (p != null) {
            nums[i--] = p.val;
            p = p.next;
        }
        return nums;
    }
}
